<script setup>
import {nextTick, reactive, ref, watch} from "vue";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  data: {
    type: Object,
    default: () => ({
      id: '',
      dictId: '',
      label: '',
      labelValue: '',
      status: '',
      sort: '',
      createTime: ''
    })
  }
})

const rules =  reactive({
  label: [
    {required: true, message: '键名不能为空', trigger: 'blur'}
  ],
  labelValue: [
    {required: true, message: '键值不能为空', trigger: 'blur'}
  ]
})

const emit = defineEmits(['update:visible', 'confirm'])

const isVisible = ref(false)

const item = ref({
  id: '',
  dictId: '',
  label: '',
  labelValue: '',
  status: '',
  sort: '',
  createTime: ''
})

const statusEnum = ref([
  {label: "启用", value: 1},
  {label: "禁用", value: 2}
])

const formRef = ref(null)

watch(() =>  props.visible, (newVal) => isVisible.value = newVal)

watch(() => props.data, (newVal) => item.value = {...newVal})

const onCancel = () => {
  emit('update:visible', false)
}

const onConfirm = () => {
  if (!formRef.value) return
  formRef.value.validate(valid => {
    if (valid) {
      emit('confirm', item.value)
    }
  })
}

const handleDialogClose = () => {
  formRef.value.clearValidate()
  onCancel()
}

const resetFields = () => {
  item.value.id = ''
  nextTick(() => {
    formRef.value.resetFields()
  })
}

defineExpose({resetFields})
</script>

<template>
<el-dialog v-model="isVisible" width="360px" :close-on-click-modal="false" :title="item.id ? '新增' : '编辑'" @close="handleDialogClose">
  <el-form :model="item" ref="formRef" label-width="68px" :rules="rules">
    <el-form-item prop="label" label="键名">
      <el-input v-model="item.label" placeholder="请输入配置项名称"></el-input>
    </el-form-item>
    <el-form-item prop="labelValue" label="键值">
      <el-input v-model="item.labelValue" placeholder="请输入配置项名称"></el-input>
    </el-form-item>
    <el-form-item prop="status" label="状态">
      <el-select v-model="item.status" placeholder="请选择配置项状态">
        <el-option v-for="(statusItem, index) in statusEnum" :key="index" :label="statusItem.label" :value="statusItem.value"/>
      </el-select>
    </el-form-item>
    <el-form-item prop="sort" label="排序">
      <el-input v-model="item.sort" placeholder="请输入排序值"></el-input>
    </el-form-item>
  </el-form>
  <template #footer>
    <el-button @click="onCancel">取消</el-button>
    <el-button type="primary" @click="onConfirm">确定</el-button>
  </template>
</el-dialog>
</template>

<style scoped lang="scss">

</style>